package com.bankLogisticsSys.service;

import java.sql.Date;
import java.util.List;

import com.bankLogisticsSys.controller.WeixinApiController;
import com.bankLogisticsSys.model.Expressinfo;
import com.bankLogisticsSys.model.Networkinfo;
import com.bankLogisticsSys.util.WeixinUtil;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.weixin.sdk.api.ApiConfigKit;

public class Cron4jService {
	public static final int OVERTIME = 3;
	
	//超时提醒函数
	public List<Expressinfo> getDailyTrack(){
		Date today = new Date(System.currentTimeMillis());
		String sql = "select * from expressinfo where sendDate=? and state=1";
		return Expressinfo.dao.find(sql, today);
	}
	
	public void setOverTimeState(List<Expressinfo> eiList){
		for(Expressinfo ei:eiList){
			ei.setAbnormal(OVERTIME);
			ei.update();
		}
	}
	
	public void sendOverTimeMsg(List<Expressinfo> eiList){
		ApiConfigKit.setThreadLocalApiConfig(WeixinUtil.getApiConfig());
		WeixinApiController wac = new WeixinApiController();
		for(Expressinfo ei:eiList){
			String openId = getUser(ei.getTrackingID());
			String msg = "从" + TransformService.getNetwork(ei.getSource()) + 
					"发往" + TransformService.getNetwork(ei.getDestination()) + 
					"的快递\n已超时，请尽快处理";
			if(openId!=null){
				wac.sendProcessMsg(openId, msg);
			}
		}
	}
	public String getUser(Long trackingID){
		String employeeID = Db.queryFirst("select employeeID from expressprocess where trackingID = ? order by time desc",trackingID);
		String openId = Db.queryFirst("select openId from userinfo where employeeID = ?", employeeID);
		return openId;
	}
	
	//未派单提醒函数
	
	//获取所有需要发包的分行信息
	public List<Integer> getBankNetworkList(){
		String sql = "select id from networkinfo where type = 1";
		List<Integer> networkIdList = Db.query(sql);
		return networkIdList;
	}
	
	//获取所有需要发包的分行信息
	public List<Networkinfo> getBankNetworkListW(){
		String sql = "select * from networkinfo where type = 1";
		List<Networkinfo> networkIdList = Networkinfo.dao.find(sql);
		return networkIdList;
	}
	
	//获取尚未派单的网点的网点号
	public List<Integer> getNoTrackBank(List<Integer> networkIdList){
		List<Expressinfo> eiList = getDailyTrack();
		for(Expressinfo x:eiList){
			if(networkIdList.contains(x.getSource())){
				networkIdList.remove(x.getSource());
			}
		}
		return networkIdList;
	}
	
	//获取未派单网点的员工openid
	public String getOpenId(int networkid){
		String openId = Db.queryFirst("select openId from userinfo where networkID = ?",networkid);
		return openId;
	}
	
	public void sendNoTrackMsg(List<Integer> networkidList){
		ApiConfigKit.setThreadLocalApiConfig(WeixinUtil.getApiConfig());
		WeixinApiController wac = new WeixinApiController();
		for(int x:networkidList){
			String openId = getOpenId(x);
			String msg = "  您今日尚未派单，请尽快完成操作";
			if(openId!=null){
//				wac.sendProcessMsg(openId, msg);
				System.out.println(openId + msg);
			}
		}
	}
	
}
